<template>
  <div class="comment-statistics">
    <!-- 统计卡片 -->
    <div class="statistics-cards">
      <el-row :gutter="16">
        <el-col :span="6">
          <el-card class="stat-card total">
            <div class="stat-content">
              <div class="stat-icon">
                <el-icon><ChatDotRound /></el-icon>
              </div>
              <div class="stat-info">
                <div class="stat-number">{{ statistics.totalComments }}</div>
                <div class="stat-label">总评论数</div>
              </div>
            </div>
          </el-card>
        </el-col>
        <el-col :span="6">
          <el-card class="stat-card pending">
            <div class="stat-content">
              <div class="stat-icon">
                <el-icon><Clock /></el-icon>
              </div>
              <div class="stat-info">
                <div class="stat-number">{{ statistics.todayComments }}</div>
                <div class="stat-label">今日评论</div>
              </div>
            </div>
          </el-card>
        </el-col>
        <el-col :span="6">
          <el-card class="stat-card sensitive">
            <div class="stat-content">
              <div class="stat-icon">
                <el-icon><Warning /></el-icon>
              </div>
              <div class="stat-info">
                <div class="stat-number">
                  {{ statistics.sensitiveComments }}
                </div>
                <div class="stat-label">敏感评论</div>
              </div>
            </div>
          </el-card>
        </el-col>
        <el-col :span="6">
          <el-card class="stat-card approved">
            <div class="stat-content">
              <div class="stat-icon">
                <el-icon><Select /></el-icon>
              </div>
              <div class="stat-info">
                <div class="stat-number">
                  {{ statistics.visibleComments }}
                </div>
                <div class="stat-label">可见评论</div>
              </div>
            </div>
          </el-card>
        </el-col>
      </el-row>
    </div>

    <!-- 图表区域 -->
    <div class="charts-section">
      <el-row :gutter="16">
        <!-- 状态分布饼图 -->
        <el-col :span="12">
          <el-card>
            <template #header>
              <div class="chart-header">
                <span>评论状态分布</span>
                <el-button size="small" @click="refreshStatusChart">
                  <el-icon><Refresh /></el-icon>
                </el-button>
              </div>
            </template>
            <div ref="statusChartRef" class="chart-container" />
          </el-card>
        </el-col>

        <!-- 敏感词类型分布饼图 -->
        <el-col :span="12">
          <el-card>
            <template #header>
              <div class="chart-header">
                <span>敏感词类型分布</span>
                <el-button size="small" @click="refreshSensitiveChart">
                  <el-icon><Refresh /></el-icon>
                </el-button>
              </div>
            </template>
            <div ref="sensitiveChartRef" class="chart-container" />
          </el-card>
        </el-col>
      </el-row>

      <el-row :gutter="16" style="margin-top: 16px">
        <!-- 评论趋势折线图 -->
        <el-col :span="24">
          <el-card>
            <template #header>
              <div class="chart-header">
                <span>评论趋势</span>
                <div class="chart-controls">
                  <el-radio-group
                    v-model="trendPeriod"
                    @change="refreshTrendChart"
                  >
                    <el-radio-button value="7d">最近7天</el-radio-button>
                    <el-radio-button value="30d">最近30天</el-radio-button>
                    <el-radio-button value="90d">最近90天</el-radio-button>
                  </el-radio-group>
                  <el-button size="small" @click="refreshTrendChart">
                    <el-icon><Refresh /></el-icon>
                  </el-button>
                </div>
              </div>
            </template>
            <div ref="trendChartRef" class="chart-container trend-chart" />
          </el-card>
        </el-col>
      </el-row>
    </div>

    <!-- 详细统计表格 -->
    <div class="detailed-statistics">
      <el-card>
        <template #header>
          <span>详细统计</span>
        </template>
        <el-table :data="detailedStats" stripe>
          <el-table-column prop="metric" label="指标" width="200" />
          <el-table-column prop="value" label="数值" width="120">
            <template #default="{ row }">
              <span class="stat-value">{{ formatNumber(row.value) }}</span>
            </template>
          </el-table-column>
          <el-table-column prop="percentage" label="占比" width="120">
            <template #default="{ row }">
              <el-progress
                :percentage="row.percentage"
                :color="getProgressColor(row.percentage)"
                :show-text="false"
                style="width: 80px; margin-right: 8px"
              />
              <span>{{ row.percentage }}%</span>
            </template>
          </el-table-column>
          <el-table-column prop="description" label="说明" />
        </el-table>
      </el-card>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted, onUnmounted, nextTick } from "vue";
import { ElMessage } from "element-plus";
import {
  ChatDotRound,
  Clock,
  Warning,
  Select,
  Refresh
} from "@element-plus/icons-vue";
import * as echarts from "echarts";
import {
  getCommentStatisticsApi,
  getCommentStatusDistributionApi,
  getSensitiveTypeDistributionApi,
  type CommentStatistics
} from "@/api/comment-management";

// 响应式数据
const statusChartRef = ref<HTMLDivElement>();
const sensitiveChartRef = ref<HTMLDivElement>();
const trendChartRef = ref<HTMLDivElement>();

const trendPeriod = ref("7d");

const statistics = reactive<CommentStatistics>({
  totalComments: 0,
  deletedComments: 0,
  visibleComments: 0,
  sensitiveComments: 0,
  totalReplies: 0,
  totalLikes: 0,
  totalReplyCount: 0,
  todayComments: 0,
  yesterdayComments: 0
});

const detailedStats = ref([
  {
    metric: "总评论数",
    value: 0,
    percentage: 100,
    description: "系统中所有评论的总数"
  },
  {
    metric: "待审核评论",
    value: 0,
    percentage: 0,
    description: "等待管理员审核的评论"
  },
  {
    metric: "已通过评论",
    value: 0,
    percentage: 0,
    description: "审核通过并显示的评论"
  },
  {
    metric: "已拒绝评论",
    value: 0,
    percentage: 0,
    description: "审核拒绝的评论"
  },
  {
    metric: "已删除评论",
    value: 0,
    percentage: 0,
    description: "被删除的评论"
  },
  {
    metric: "敏感评论",
    value: 0,
    percentage: 0,
    description: "包含敏感内容的评论"
  },
  {
    metric: "回复评论",
    value: 0,
    percentage: 0,
    description: "对其他评论的回复"
  }
]);

let statusChart: echarts.ECharts | null = null;
let sensitiveChart: echarts.ECharts | null = null;
let trendChart: echarts.ECharts | null = null;

// 生命周期
onMounted(() => {
  loadStatistics();
  nextTick(() => {
    initCharts();
  });

  // 监听窗口大小变化
  window.addEventListener("resize", handleResize);
});

onUnmounted(() => {
  // 销毁图表实例
  statusChart?.dispose();
  sensitiveChart?.dispose();
  trendChart?.dispose();

  window.removeEventListener("resize", handleResize);
});

// 方法
const loadStatistics = async () => {
  try {
    const response = await getCommentStatisticsApi();
    if (response.code === 200 && response.data) {
      Object.assign(statistics, response.data);
      updateDetailedStats();
    }
  } catch (error) {
    console.error("加载统计数据失败:", error);
    ElMessage.error("加载统计数据失败");
  }
};

const updateDetailedStats = () => {
  const total = statistics.totalComments || 1; // 避免除零

  detailedStats.value = [
    {
      metric: "总评论数",
      value: statistics.totalComments,
      percentage: 100,
      description: "系统中所有评论的总数"
    },
    {
      metric: "可见评论",
      value: statistics.visibleComments,
      percentage: Math.round((statistics.visibleComments / total) * 100),
      description: "当前可见的评论数量"
    },
    {
      metric: "已删除评论",
      value: statistics.deletedComments,
      percentage: Math.round((statistics.deletedComments / total) * 100),
      description: "被删除的评论"
    },
    {
      metric: "敏感评论",
      value: statistics.sensitiveComments,
      percentage: Math.round((statistics.sensitiveComments / total) * 100),
      description: "包含敏感内容的评论"
    },
    {
      metric: "总回复数",
      value: statistics.totalReplies,
      percentage: Math.round((statistics.totalReplies / total) * 100),
      description: "所有评论的回复总数"
    },
    {
      metric: "总点赞数",
      value: statistics.totalLikes,
      percentage: Math.round((statistics.totalLikes / total) * 100),
      description: "所有评论获得的点赞总数"
    },
    {
      metric: "今日评论",
      value: statistics.todayComments,
      percentage: Math.round((statistics.todayComments / total) * 100),
      description: "今天新增的评论数量"
    },
    {
      metric: "昨日评论",
      value: statistics.yesterdayComments,
      percentage: Math.round((statistics.yesterdayComments / total) * 100),
      description: "昨天新增的评论数量"
    }
  ];
};

const initCharts = () => {
  initStatusChart();
  initSensitiveChart();
  initTrendChart();
};

const initStatusChart = async () => {
  if (!statusChartRef.value) return;

  statusChart = echarts.init(statusChartRef.value);

  try {
    const response = await getCommentStatusDistributionApi();
    if (response.code === 200 && response.data) {
      const chartData = Object.entries(response.data).map(([key, value]) => ({
        name: getStatusName(key),
        value: value as number
      }));

      const option = {
        tooltip: {
          trigger: "item",
          formatter: "{a} <br/>{b}: {c} ({d}%)"
        },
        legend: {
          orient: "vertical",
          left: "left"
        },
        series: [
          {
            name: "评论状态",
            type: "pie",
            radius: "50%",
            data: chartData,
            emphasis: {
              itemStyle: {
                shadowBlur: 10,
                shadowOffsetX: 0,
                shadowColor: "rgba(0, 0, 0, 0.5)"
              }
            }
          }
        ]
      };

      statusChart.setOption(option);
    }
  } catch (error) {
    console.error("加载状态分布数据失败:", error);
  }
};

const initSensitiveChart = async () => {
  if (!sensitiveChartRef.value) return;

  sensitiveChart = echarts.init(sensitiveChartRef.value);

  try {
    const response = await getSensitiveTypeDistributionApi();
    if (response.code === 200 && response.data) {
      const chartData = Object.entries(response.data).map(([key, value]) => ({
        name: getSensitiveTypeName(key),
        value: value as number
      }));

      const option = {
        tooltip: {
          trigger: "item",
          formatter: "{a} <br/>{b}: {c} ({d}%)"
        },
        legend: {
          orient: "vertical",
          left: "left"
        },
        series: [
          {
            name: "敏感词类型",
            type: "pie",
            radius: "50%",
            data: chartData,
            emphasis: {
              itemStyle: {
                shadowBlur: 10,
                shadowOffsetX: 0,
                shadowColor: "rgba(0, 0, 0, 0.5)"
              }
            }
          }
        ]
      };

      sensitiveChart.setOption(option);
    }
  } catch (error) {
    console.error("加载敏感词类型分布数据失败:", error);
  }
};

const initTrendChart = () => {
  if (!trendChartRef.value) return;

  trendChart = echarts.init(trendChartRef.value);

  // 模拟趋势数据
  const dates = generateDateRange(parseInt(trendPeriod.value));
  const commentData = dates.map(() => Math.floor(Math.random() * 100) + 20);
  const sensitiveData = dates.map(() => Math.floor(Math.random() * 20) + 5);

  const option = {
    tooltip: {
      trigger: "axis"
    },
    legend: {
      data: ["评论数", "敏感评论数"]
    },
    grid: {
      left: "3%",
      right: "4%",
      bottom: "3%",
      containLabel: true
    },
    xAxis: {
      type: "category",
      boundaryGap: false,
      data: dates
    },
    yAxis: {
      type: "value"
    },
    series: [
      {
        name: "评论数",
        type: "line",
        stack: "Total",
        data: commentData,
        smooth: true,
        itemStyle: {
          color: "#409eff"
        }
      },
      {
        name: "敏感评论数",
        type: "line",
        stack: "Total",
        data: sensitiveData,
        smooth: true,
        itemStyle: {
          color: "#f56c6c"
        }
      }
    ]
  };

  trendChart.setOption(option);
};

const refreshStatusChart = () => {
  initStatusChart();
};

const refreshSensitiveChart = () => {
  initSensitiveChart();
};

const refreshTrendChart = () => {
  initTrendChart();
};

const handleResize = () => {
  statusChart?.resize();
  sensitiveChart?.resize();
  trendChart?.resize();
};

// 工具方法
const formatNumber = (num: number): string => {
  if (num >= 10000) {
    return (num / 10000).toFixed(1) + "万";
  } else if (num >= 1000) {
    return (num / 1000).toFixed(1) + "k";
  }
  return num.toString();
};

const getProgressColor = (percentage: number): string => {
  if (percentage < 30) return "#67c23a";
  if (percentage < 70) return "#e6a23c";
  return "#f56c6c";
};

const getStatusName = (status: string): string => {
  const statusMap: Record<string, string> = {
    "0": "待审核",
    "1": "已通过",
    "2": "已拒绝",
    "3": "已删除"
  };
  return statusMap[status] || status;
};

const getSensitiveTypeName = (type: string): string => {
  const typeMap: Record<string, string> = {
    profanity: "脏话",
    politics: "政治敏感",
    advertisement: "广告",
    violence: "暴力内容",
    illegal: "违法内容",
    spam: "垃圾信息"
  };
  return typeMap[type] || type;
};

const generateDateRange = (days: number): string[] => {
  const dates: string[] = [];
  const today = new Date();

  for (let i = days - 1; i >= 0; i--) {
    const date = new Date(today);
    date.setDate(today.getDate() - i);
    dates.push(date.toLocaleDateString());
  }

  return dates;
};
</script>

<style scoped lang="scss">
.comment-statistics {
  .statistics-cards {
    margin-bottom: 20px;

    .stat-card {
      height: 120px;
      cursor: pointer;
      transition: all 0.3s ease;

      &:hover {
        box-shadow: 0 4px 12px rgb(0 0 0 / 10%);
        transform: translateY(-2px);
      }

      :deep(.el-card__body) {
        display: flex;
        align-items: center;
        height: 100%;
        padding: 20px;
      }

      .stat-content {
        display: flex;
        align-items: center;
        width: 100%;

        .stat-icon {
          margin-right: 16px;
          font-size: 40px;
          opacity: 0.8;
        }

        .stat-info {
          .stat-number {
            margin-bottom: 4px;
            font-size: 28px;
            font-weight: bold;
          }

          .stat-label {
            font-size: 14px;
            color: #909399;
          }
        }
      }

      &.total {
        .stat-icon {
          color: #409eff;
        }

        .stat-number {
          color: #409eff;
        }
      }

      &.pending {
        .stat-icon {
          color: #e6a23c;
        }

        .stat-number {
          color: #e6a23c;
        }
      }

      &.sensitive {
        .stat-icon {
          color: #f56c6c;
        }

        .stat-number {
          color: #f56c6c;
        }
      }

      &.approved {
        .stat-icon {
          color: #67c23a;
        }

        .stat-number {
          color: #67c23a;
        }
      }
    }
  }

  .charts-section {
    margin-bottom: 20px;

    .chart-header {
      display: flex;
      align-items: center;
      justify-content: space-between;

      .chart-controls {
        display: flex;
        gap: 12px;
        align-items: center;
      }
    }

    .chart-container {
      height: 300px;

      &.trend-chart {
        height: 400px;
      }
    }
  }

  .detailed-statistics {
    .stat-value {
      font-weight: 600;
      color: #303133;
    }
  }
}
</style>
